import {
    Card,
    Breadcrumb,
    Form,
    Button,
    Radio,
    Input,
    Upload,
    Space,
    Select,
    message
} from 'antd'
import ReactQuill from 'react-quill'
import 'react-quill/dist/quill.snow.css'
import { PlusOutlined } from '@ant-design/icons'
import { Link, useNavigate, useSearchParams } from 'react-router-dom'
import './index.scss'
import { useEffect, useState } from 'react'
import { addArticleAPI, getArticleId, updateArticleAPI, } from '@/apis/article'
import { useChannel } from '@/hooks/useChannel'

const { Option } = Select

const Publish = () => {
    const navigate = useNavigate()
    // 获取频道列表
    const { channelList } = useChannel()
    // 切换图片封面类型
    const [type, setType] = useState(0)
    // 上传图片
    const [imageList, setImageList] = useState([])
    // 提交表单数据
    const onFinish = (value) => {
        const { title, content, channel_id } = value
        const data = {
            title,
            content,
            cover: {
                type,
                images: imageList.map(item => {
                    if(item.response){
                        return item.response.data.url
                    }else{
                        return item.url
                    }
                })
            },
            channel_id
        }
        // 校验图片数量和列表数量是否相等
        if (imageList.length !== type) {
            return message.warning("封面类型和图片数量不匹配")
        }
        // 根据是否有id调用不同接口
        if(articleId){
            updateArticleAPI({...data,id:articleId})
        }else{
            addArticleAPI(data)
        }
        navigate('/article')
    }
    const onchange = (value) => {
        setImageList(value.fileList)
    }
    const onRadioChange = (value) => {
        setType(value.target.value)
    }
    // 回填数据
    const [searchParams] = useSearchParams()
    const articleId = searchParams.get('id')
    // 获取实例
    const [form] = Form.useForm()
    useEffect(() => {
        // 1. 通过id获取数据
        const getArticleDetail = async () => {
            const res = await getArticleId(articleId)
            const data = res.data
            form.setFieldsValue({
                ...data,
                type:data.cover.type
            })
            // 回填图片列表
            setType(data.cover.type)
            // 显示图片
            setImageList(data.cover.images.map(url=>{
                return {url}
            }))
        }
        // 只有有id的时候才能调用此函数回填
        if (articleId) {
            getArticleDetail()
        }
        // 2. 调用实例方法 完成回填
    }, [articleId, form])
    // 获取实例
    return (
        <div className="publish">
            <Card
                title={
                    <Breadcrumb items={[
                        { title: <Link to={'/home'}>首页</Link> },
                        { title: `${articleId ? '编辑文章':'发布文章'}` },
                    ]}
                    />
                }
            >
                <Form
                    form={form}
                    labelCol={{ span: 4 }}
                    wrapperCol={{ span: 16 }}
                    initialValues={{ type: 0 }}
                    onFinish={onFinish}
                    
                >
                    <Form.Item
                        label="标题"
                        name="title"
                        rules={[{ required: true, message: '请输入文章标题' }]}
                    >
                        <Input placeholder="请输入文章标题" style={{ width: 400 }} />
                    </Form.Item>
                    <Form.Item
                        label="频道"
                        name="channel_id"
                        rules={[{ required: true, message: '请选择文章频道' }]}
                    >
                        <Select placeholder="请选择文章频道" style={{ width: 400 }}>
                            {
                                channelList.map(item => {
                                    return <Option key={item.id} value={item.id}>{item.name}</Option>
                                })
                            }
                        </Select>
                    </Form.Item>
                    <Form.Item label="封面">
                        <Form.Item name="type">
                            <Radio.Group onChange={onRadioChange}>
                                <Radio value={1}>单图</Radio>
                                <Radio value={3}>三图</Radio>
                                <Radio value={0}>无图</Radio>
                            </Radio.Group>
                        </Form.Item>
                        {/* 
                            listType：决定选择文件框的外观样式
                            showUploadList:展示选择的图片列表
                        */}
                        {
                            type > 0 ? <Upload
                                listType="picture-card"
                                showUploadList
                                name="image"
                                maxCount={type}
                                action={'http://geek.itheima.net/v1_0/upload'}
                                onChange={onchange}
                                fileList={imageList}
                            >
                                <div style={{ marginTop: 8 }}>
                                    <PlusOutlined />
                                </div>
                            </Upload> : <></>
                        }
                    </Form.Item>
                    <Form.Item
                        label="内容"
                        name="content"
                        rules={[{ required: true, message: '请输入文章内容' }]}
                    >
                        <ReactQuill
                            className="publish-quill"
                            theme="snow"
                            placeholder="请输入文章内容"
                        />
                    </Form.Item>

                    <Form.Item wrapperCol={{ offset: 4 }}>
                        <Space>
                            <Button size="large" type="primary" htmlType="submit">
                                {`${articleId ? '更新文章':'发布文章'}`}
                            </Button>
                        </Space>
                    </Form.Item>
                </Form>
            </Card>
        </div>
    )
}

export default Publish